/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eu.fsiebert.polytech.db.mediatheque.session;

import eu.fsiebert.polytech.db.mediatheque.entity.Adherent;
import java.util.Random;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Florent
 */
@Stateless
public class AdherentFacade extends AbstractFacade<Adherent> {
    @PersistenceContext(unitName = "mediatheque")
    private EntityManager em;
    
    private static final char[] passwordAuthorizedCharacters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    private static final int generatedPasswordLength = 6;
    private static Random randomGenerator = new Random();

    protected EntityManager getEntityManager() {
        return em;
    }

    public AdherentFacade() {
        super(Adherent.class);
    }

    @Override
    public void create(Adherent entity) {
        if(checkPassword(entity.getPassword())) {
            super.create(entity);
        }
    }
    
    public String getRandomPassword() {
        StringBuilder builder = new StringBuilder();
        for (int i = 0 ; i < generatedPasswordLength ; i++) {
	    builder.append(passwordAuthorizedCharacters[randomGenerator.nextInt(passwordAuthorizedCharacters.length)]);
	}
        return builder.toString();
    }

    
    private boolean checkPassword(String password) {
        char[] passwordCharacters = password.toCharArray();
        for(char character : passwordCharacters) {
            if(!checkValidPasswordCharacter(character)) {
                return false;
            }
        }
        return true;
    }

    private boolean checkValidPasswordCharacter(char character) {
        for(char c : passwordAuthorizedCharacters) {
            if(character == c) {
                return true;
            }
        }
        return false;
    }
        
    public Adherent getByLoginPassword(String login, String password){
        Query query = em.createNamedQuery("Adherent.findByLoginAndPassword", Adherent.class);
        query.setParameter("login", login);
        query.setParameter("password", password);
        query.setMaxResults(20);
        try{
            return (Adherent) query.getSingleResult();
        }catch(NoResultException e){
            return null;
        }
    }

    public void merge(Adherent user) {
        em.merge(user);
    }
}
